// Test huhu
package sheep.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.LinkedList;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;
import org.jdesktop.fuse.ResourceInjector;
import org.jdesktop.swingx.JXCollapsiblePane;
import org.jdesktop.swingx.JXPanel;
import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.StackLayout;
import sheep.controller.Workspace;
import sheep.model.WorkGroup;
import sheep.model.Worker;
import sheep.view.Component.UserTableModel;
import sheep.view.Component.ActionButton;
import sheep.view.Component.GroupTableModel;
import sheep.view.Component.RoundedPanel;
import sheep.view.Component.SheepScrollbarUI;
import sheep.view.Component.UserCellRenderer;
import sheep.view.Component.UsersChooser;

public class UserPanel extends JPanel {

  private Workspace workspace;
  
  //private final BackgroundMenuTitle backgroundTitle;
  private final JPanel mainPanel;
  ///////////////////////////////////////////////////////////////////////////
  // Panneau users
  private final JPanel leftPanel;
  private final JPanel usersButtonPanel;
  private final JPanel usersContentPanel;
  private UsersChooser userChooser;
  private JXTable usersTable;
  private UserTableModel usersTableModel;
  private JXCollapsiblePane collapser;
  // Popup
  private UserEditPanel userEditPanel; 
  ///////////////////////////////////////////////////////////////////////////
  // Panneau Groupes
  private final JPanel rightPanel;
  private final JPanel groupsButtonPanel;
  private final JPanel groupsContentPanel;
  private JXTable groupsTable;
  private GroupTableModel groupsTableModel;
  
  // Popup
  private WorkGroupEditPanel workGroupEditPanel;
  
  public UserPanel(final Workspace workspace) {

    this.workspace = workspace;
    
    ResourceInjector.get().inject(this);

    setOpaque(false);
    setLayout(new BorderLayout());
    setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
    ////////////////////////////////////////////////////////////////////////
    // Panel principal
    ////////////////////////////////////////////////////////////////////////
    mainPanel = new JPanel();
    mainPanel.setOpaque(false);
    BorderLayout mainPanelLayout = new BorderLayout();
    mainPanelLayout.setHgap(15);
    mainPanel.setLayout(mainPanelLayout);
    //add(mainPanel,BorderLayout.CENTER);
    
    ////////////////////////////////////////////////////////////////////////

    ////////////////////////////////////////////////////////////////////////
    // Panel des utilisateurs
    ////////////////////////////////////////////////////////////////////////
    leftPanel = new JPanel();
    leftPanel.setOpaque(false);
    BorderLayout leftPanelLayout = new BorderLayout();
    leftPanelLayout.setVgap(15);
    leftPanel.setLayout(leftPanelLayout);
    
    ////////////////////////////////////////////////////////////////////////
    // CrÃ©ation de la zone d'affichage des utilisateurs (en haut)    
    usersContentPanel = new JPanel();
    usersContentPanel.setOpaque(false);
    BorderLayout usersContentPanelLayout = new BorderLayout();
    usersContentPanel.setLayout(usersContentPanelLayout);
    
    TableCellRenderer render = new UserCellRenderer();
    Object headers[] = { "Numéro", "Prénom", "Nom", "Job" };  
    usersTable = new JXTable();
    usersTable.setShowVerticalLines(false);
    usersTable.setGridColor(Color.LIGHT_GRAY);
    usersTableModel = new UserTableModel(headers, workspace.getWorkersList());
    
    usersTable.setModel(usersTableModel);
    UserTableModel.setTableHeaders(usersTable, usersTableModel.getHeaders());
    userChooser = new UsersChooser(workspace.getWorkersList(), UsersChooser.Mode.USER_PANEL);
    userChooser.setChooserWidth(75);
    userChooser.setChooserHeight(90);
    Component[] comp ={usersTable}; 
    userChooser.setRepaintComponent(comp);
    usersTable.setDefaultRenderer(Object.class, render);
    usersTable.setColumnControlVisible(true);
    usersTable.setRowHeight(50);
    usersTable.setFocusable(false);
    usersTable.packAll();
    usersTable.setColumnSelectionAllowed(false);
    usersTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    usersTable.setEditable(false);
    usersTable.addMouseListener(new MouseListener(){

      public void mouseClicked(MouseEvent e) {
        if(usersTable.getSelectedRow()>=0){
         Object tb = usersTableModel.getValueAt(usersTable.getSelectedRow(), 0);
         Worker wk = workspace.getWorker(tb);
        if(e.getClickCount()==2 && e.getButton()==1) {
          userEditPanel.setWorker(wk);
          userEditPanel.setFieldsValues();
          userEditPanel.setVisible(!userEditPanel.isVisible());
        }
          workspace.setCurrentWorker(wk);
          userChooser.scrollPos(usersTable.getSelectedRow());
          //userChooser.setSelected(usersTable.getSelectedRow());
        }
      }
      
      public void mousePressed(MouseEvent e) {}
      public void mouseReleased(MouseEvent e) {}
      public void mouseEntered(MouseEvent e) {}
      public void mouseExited(MouseEvent e) {}
    });
    
    usersTable.setPreferredSize(new Dimension (700, 700));
    
    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.setViewportView(usersTable);
    scrollPane.getVerticalScrollBar().setUI(new SheepScrollbarUI());
    
    userEditPanel = new UserEditPanel(workspace, null, usersTable, usersTableModel, this);   
    JXPanel centerSatckPanel = new JXPanel(new StackLayout());
    centerSatckPanel.setOpaque(false);
    centerSatckPanel. add(scrollPane, StackLayout.TOP);
    userEditPanel.setVisible2(false);
    centerSatckPanel.add(userEditPanel,StackLayout.TOP );    
    usersContentPanel.add(centerSatckPanel, BorderLayout.CENTER);
    
    
    collapser = new JXCollapsiblePane();
    collapser.setOpaque(false);
    collapser.setLayout(new BorderLayout());
    collapser.setCollapsed(true);
    collapser.setContentPane(new ContentPanel());
    userChooser.setOpaque(false);
    collapser.add(userChooser, BorderLayout.SOUTH);
    
    userChooser.setSpacing(0.4);
    userChooser.setAmount(workspace.getWorkersList().size());
    usersContentPanel.add(collapser, BorderLayout.SOUTH);
    
    ////////////////////////////////////////////////////////////////////////
    // CrÃ©ation de la zone de boutons (en bas)
    usersButtonPanel = new JPanel();  
    usersButtonPanel.setOpaque(false);

    JButton ajoutUserBttn = new ActionButton("Ajouter");
    ajoutUserBttn.addActionListener(new ActionListener(){
      @Override
      public void actionPerformed(ActionEvent e) {
        userEditPanel.setWorker(null);
        userEditPanel.setFieldsValues();
        userEditPanel.setVisible(!userEditPanel.isVisible());
      }
    });
    usersButtonPanel.add(ajoutUserBttn);
    
    JButton modifUserBttn = new ActionButton("Modifier");
    modifUserBttn.addActionListener(new ActionListener(){
      @Override
      public void actionPerformed(ActionEvent e) {
        if (usersTable.getSelectedRow()!=-1){
          Object tb = usersTableModel.getValueAt(usersTable.getSelectedRow(), 0);
          Worker wk = workspace.getWorker(tb);
          userEditPanel.setWorker(wk);
          userEditPanel.setFieldsValues();
          userEditPanel.setVisible(!userEditPanel.isVisible());
        }
      }
    });
    usersButtonPanel.add(modifUserBttn);
    
    JButton deleteUserBttn = new ActionButton("Supprimer");
    deleteUserBttn.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent arg0) {
        if (usersTable.getSelectedRow()!=-1){
          if(usersTable.getSelectedRow() < usersTableModel.getRowCount()) {
            Object tb = usersTableModel.getValueAt(usersTable.getSelectedRow(), 0);
            Worker wk = workspace.getWorker(tb);
            LinkedList<Worker> list = workspace.getWorkersList();
            list.remove(wk);
            workspace.setWorkersList(list);
            usersTableModel.setData(workspace.getWorkersList());
            usersTable.setModel(usersTableModel);
            usersTable.repaint();
            refresh();
          }
        }
      }
    });
    usersButtonPanel.add(deleteUserBttn);
    
    ActionButton collapserBtttn = new ActionButton("Portrait");
    collapserBtttn.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e) {
        collapser.setCollapsed(!collapser.isCollapsed());
      }
    });
    collapserBtttn.setMain(true);
    
    usersButtonPanel.add(collapserBtttn);
    
    JPanel temp = new JPanel();
    temp.setOpaque(false);
    BorderLayout leftPanelLayout2 = new BorderLayout();
    leftPanelLayout2.setVgap(15);
    temp.setLayout(leftPanelLayout2);
    temp.add(usersContentPanel,BorderLayout.CENTER);
    temp.add(usersButtonPanel,BorderLayout.SOUTH);
    
    
    JLabel collabNam = new JLabel();
    collabNam.setFont(new java.awt.Font("Times New Roman", 1, 24));
    collabNam.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    collabNam.setText("COLLABORATEURS");
    collabNam.setForeground(new java.awt.Color(255, 255, 255));
    leftPanel.add(collabNam, java.awt.BorderLayout.NORTH);    
    
    
    leftPanel.add(new RoundedPanel(temp),BorderLayout.CENTER);
    
    
    ////////////////////////////////////////////////////////////////////////
    // Panel des groupes
    ////////////////////////////////////////////////////////////////////////
    rightPanel = new JPanel();
    rightPanel.setOpaque(false);
    BorderLayout rightPanelLayout = new BorderLayout();
    rightPanelLayout.setVgap(15);
    rightPanel.setLayout(rightPanelLayout);
    
    ////////////////////////////////////////////////////////////////////////
    // CrÃ©ation de la zone d'affichage des groups (en haut)    
    groupsContentPanel = new JPanel();
    groupsContentPanel.setOpaque(false);
    BorderLayout groupsContentPanelLayout = new BorderLayout();
    groupsContentPanel.setLayout(groupsContentPanelLayout);
    
    TableCellRenderer groupsRender = new UserCellRenderer();
    Object groupsHeaders[] = { "Numéro", "Nom", "# de personnes" };  
    groupsTable = new JXTable();
    groupsTableModel = new GroupTableModel(groupsHeaders, workspace.getWorkGroupsList());
    groupsTable.setModel(groupsTableModel);
    groupsTable.setShowVerticalLines(false);
    groupsTable.setGridColor(Color.LIGHT_GRAY);
    UserTableModel.setTableHeaders(groupsTable, groupsTableModel.getHeaders());
    groupsTable.setDefaultRenderer(Object.class, groupsRender);
    groupsTable.setColumnControlVisible(true);
    groupsTable.setRowHeight(50);
    groupsTable.packAll();
    groupsTable.setColumnSelectionAllowed(false);
    groupsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    groupsTable.setEditable(false);
    groupsTable.addMouseListener(new MouseListener(){

      public void mouseClicked(MouseEvent e) {
        if(e.getClickCount()==2 && e.getButton()==1) {
          Object tb = groupsTableModel.getValueAt(groupsTable.getSelectedRow(), 0);
          WorkGroup wg = workspace.getWorkGroup(tb);
          workGroupEditPanel.setWorkGroup(wg);
          workGroupEditPanel.setFieldsValues();
          workGroupEditPanel.setVisible(!workGroupEditPanel.isVisible());
        }    
      }

      public void mousePressed(MouseEvent e) {}
      public void mouseReleased(MouseEvent e) {}
      public void mouseEntered(MouseEvent e) {}
      public void mouseExited(MouseEvent e) {}
    });
    
    JScrollPane groupsScrollPane = new JScrollPane();
    groupsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    groupsScrollPane.setViewportView(groupsTable);
    groupsScrollPane.getVerticalScrollBar().setUI(new SheepScrollbarUI());
    
    JXPanel groupsCenterSatckPanel = new JXPanel(new StackLayout());
    workGroupEditPanel = new WorkGroupEditPanel(workspace, null, groupsTable, groupsTableModel);   
    groupsCenterSatckPanel.setOpaque(false);
    groupsCenterSatckPanel.add(groupsScrollPane, StackLayout.TOP);
    
    centerSatckPanel.add(workGroupEditPanel,StackLayout.TOP ); 
    workGroupEditPanel.setVisible2(false);  
    groupsContentPanel.add(groupsCenterSatckPanel, BorderLayout.CENTER);
    
    
    ////////////////////////////////////////////////////////////////////////
    // CrÃ©ation de la zone de boutons (en bas)
    groupsButtonPanel = new JPanel();  
    groupsButtonPanel.setOpaque(false);

    JButton ajoutGroupBttn = new ActionButton("Ajouter");
    ajoutGroupBttn.addActionListener(new ActionListener(){
      @Override
      public void actionPerformed(ActionEvent e) {
        workGroupEditPanel.setWorkGroup(null);
        workGroupEditPanel.setFieldsValues();
        workGroupEditPanel.setVisible(!workGroupEditPanel.isVisible());
      }
    });
    groupsButtonPanel.add(ajoutGroupBttn);
    
    JButton modifGroupBttn = new ActionButton("Modifier");
    modifGroupBttn.addActionListener(new ActionListener(){
      @Override
      public void actionPerformed(ActionEvent e) {
        Object tb = groupsTableModel.getValueAt(groupsTable.getSelectedRow(), 0);
        WorkGroup wk = workspace.getWorkGroup(tb);
        workGroupEditPanel.setWorkGroup(wk);
        workGroupEditPanel.setFieldsValues();
        workGroupEditPanel.setVisible(!workGroupEditPanel.isVisible());
      }
    });
    groupsButtonPanel.add(modifGroupBttn);
    
    JButton deleteGroupBttn = new ActionButton("Supprimer");
    deleteGroupBttn.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent arg0) {
          if(groupsTable.getSelectedRow() < groupsTableModel.getRowCount()) {
            Object tb = groupsTableModel.getValueAt(groupsTable.getSelectedRow(), 0);
            WorkGroup wk = workspace.getWorkGroup(tb);
            LinkedList<WorkGroup> list = workspace.getWorkGroupsList();
            list.remove(wk);
            workspace.setWorkGroupsList(list);
            groupsTableModel.setData(workspace.getWorkGroupsList());
            groupsTable.setModel(groupsTableModel);
            groupsTable.repaint();
          }
      }
    });
    groupsButtonPanel.add(deleteGroupBttn);
    
    JButton groupsCollapserBtttn = new ActionButton("Surprise !!!");
    //groupsCollapserBtttn.addActionListener(new ActionListener(){
     // public void actionPerformed(ActionEvent e) {
        //collapser.setCollapsed(!collapser.isCollapsed());
      //}
    //});
    groupsButtonPanel.add(groupsCollapserBtttn);
    

    JPanel temp2 = new JPanel();
    temp2.setOpaque(false);
    BorderLayout leftPanelLayout3 = new BorderLayout();
    leftPanelLayout3.setVgap(15);
    temp2.setLayout(leftPanelLayout3);
    temp2.add(groupsContentPanel,BorderLayout.CENTER);
    temp2.add(groupsButtonPanel,BorderLayout.SOUTH);
    
    JLabel groupNam = new JLabel();
    groupNam.setFont(new java.awt.Font("Times New Roman", 1, 24));
    groupNam.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    groupNam.setText("GROUPES");
    groupNam.setForeground(new java.awt.Color(255, 255, 255));
    rightPanel.add(groupNam, java.awt.BorderLayout.NORTH);    
    
    
    rightPanel.add(new RoundedPanel(temp2),BorderLayout.CENTER);
    

    


    mainPanel.add(leftPanel, BorderLayout.CENTER);
    //mainPanel.add(rightPanel, BorderLayout.EAST);
    
    add(mainPanel, BorderLayout.CENTER);

    ////////////////////////////////////////////////////////////////////////
  }

  void refresh() {

    userChooser.setAmount(workspace.getWorkersList().size());
    userChooser.findAvatars();
    userChooser.refresh();
    userChooser.repaint();
    
    if( workspace.getCurrentWorker()!= null){
      Worker wk;
      Object tb;
      for (int i = 0; i < usersTable.getModel().getRowCount(); i++){
        tb = usersTableModel.getValueAt(i, 0);
        wk = workspace.getWorker(tb);
        if (wk.getId() == workspace.getCurrentWorker().getId()){
          usersTable.setRowSelectionInterval(i, i);         
          userChooser.refresh();
          
        }
      }      
    }
    userChooser.scrollPos(usersTable.getModel().getRowCount()-1);
    repaint();
  }

}
